package org.jeecg.modules.system.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import io.netty.util.internal.StringUtil;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.*;
import org.jeecg.enums.common.DataScopeEnum;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.model.TreeModel;
import org.jeecg.modules.system.service.*;
import org.jeecg.modules.system.vo.SysUserRoleScope;
import org.jeecg.modules.system.vo.SysUserRoleScopeResponse;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.system.vo.SysUserPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 用户管理
 * @Author: jeecg-boot
 * @Date:   2019-08-04
 * @Version: V1.0
 */
@RestController
@RequestMapping("/b/sys/userNew")
@Slf4j
public class SysUserNewController {
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserPositionService sysUserPositionService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysPositionService sysPositionService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysScopeService sysScopeService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysDepartPositionService sysDepartPositionService;
    @Autowired
    @Lazy
    private RedisUtil redisUtil;
     /**
	  * 分页列表查询
	 * @param sysUser
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<SysUser>> list(SysUser sysUser,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
	     Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
         sysUser.setSqlMap(sysUserRoleService.dataScopeDepartOnlyFilter(SsoUtil.getLoginUser(),"d",sysUser.getMenuPath(),"a",null));
         Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
         page.setRecords(sysUserService.findPage(page, sysUser));
         result.setSuccess(true);
		 result.setResult(page);
		 return result;
	}

	@PutMapping(value = "/autoAccount")
	public Result autoAccount(@RequestParam(value = "userId",required = true) String userId,
                              @RequestParam(value = "userName",required = true) String userName){
        //检查是否有岗位
        List<SysDepartPosition> sysDepartPositions = sysUserPositionService.selectPositionId(userId);
        if (sysDepartPositions.size() <= 0){
            return Result.error("开通账号前,需入岗！");
        }
        try{
            sysUserService.autoAccount(userId,SsoUtil.getLoginUser());
            redisUtil.del(CacheConstant.LOGIN_USER + "::" + userName);
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error("系统繁忙,开通失败!");
        }
	    return Result.ok("开通成功");
    }


     /**
      * 根据岗位查询
      * @param sysUser
      * @param pageNo
      * @param pageSize
      * @param req
      * @return
      */
	@GetMapping(value = "/listByPosition")
	public Result<IPage<SysUser>> listByPosition(SysUser sysUser,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
	     Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
         sysUser.setSqlMap(sysUserRoleService.dataScopeDepartOnlyFilter(SsoUtil.getLoginUser(),"d",sysUser.getMenuPath(),"a",null));
         Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
         page.setRecords(sysUserService.findPageByPosition(page, sysUser));
         result.setSuccess(true);
		 result.setResult(page);
		 return result;
	}

	/**
	  *   添加
	 * @param sysUserPage
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result add(@RequestBody SysUserPage sysUserPage) {
		try {
			SysUser sysUser = new SysUser();
			if (StringUtils.isEmpty(sysUserPage.getDepartId())){
			    return Result.error("请选择该人员的部门");
            }
			//获取该人员部门上级公司
            SysDepart sysDepart = sysDepartService.getCompanyByDepartId(sysUserPage.getDepartId());
            String salt = oConvertUtils.randomGen(8);
            sysUserPage.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(sysUserPage.getUsername(), sysUserPage.getPassword(), salt);
			sysUserPage.setPassword(passwordEncode);
			sysUserPage.setStatus(1);
			sysUserPage.setDelFlag("0");
            BeanUtils.copyProperties(sysUserPage, sysUser);
            sysUser.setCompanyId(sysDepart.getId());
            SysUser user = sysUserService.getUserByName(sysUser.getUsername());
            if (user != null){
                return Result.error("登录账号已存在,添加失败!");
            }
            sysUserService.save(sysUser);
            String userId = sysUser.getId();
            //部门
            String departId = sysUserPage.getDepartId();
            //岗位
            String[] receiveAttr = sysUserPage.getReceiveAttr();
            List<String> departPositionList = Arrays.asList(receiveAttr);
            //查询部门岗位表所对应入职岗位
            List<SysDepartPosition> sysDepartPositions = sysDepartPositionService.selectPositionList(departPositionList);
            sysUserPositionService.addBatch(userId,departId,sysDepartPositions);
            return Result.ok("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return Result.error("操作失败");
		}
	}
	
	/**
	  *  编辑
	 * @param sysUserPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<SysUser> edit(@RequestBody SysUserPage sysUserPage) {

		Result<SysUser> result = new Result<SysUser>();
		SysUser sysUser = new SysUser();
		BeanUtils.copyProperties(sysUserPage, sysUser);
		SysUser sysUserEntity = sysUserService.getById(sysUser.getId());
		if(sysUserEntity==null) {
			result.error500("未找到对应实体");
		}else {
		    //判断是否修改密码
            if (StringUtils.isNotBlank(sysUser.getPassword())){
                String salt = oConvertUtils.randomGen(8);
                sysUser.setSalt(salt);
                String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), sysUser.getPassword(), salt);
                sysUser.setPassword(passwordEncode);
            }
            sysUserService.updateById(sysUser);
            String[] receiveAttr = sysUserPage.getReceiveAttr();
            List<String> departPositionList = Arrays.asList(receiveAttr);
            String oldDepartId = sysUserService.selectDepart(sysUser.getId());
            String newDepartId = sysUser.getDepartId();
            //查询部门岗位表所对应入职岗位
            List<SysDepartPosition> sysDepartPositions = sysDepartPositionService.selectPositionList(departPositionList);
            sysUserPositionService.editBatch(sysUser.getId(),oldDepartId,newDepartId,sysDepartPositions);
            redisUtil.del(CacheConstant.LOGIN_USER +"::"+sysUser.getUsername());
            result.success("修改成功!");
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			sysUserService.delMain(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<SysUser> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<SysUser> result = new Result<SysUser>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.sysUserService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<SysUser> queryById(@RequestParam(name="id",required=true) String id) {
		Result<SysUser> result = new Result<SysUser>();
		SysUser sysUser = sysUserService.getById(id);
		if(sysUser==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(sysUser);
			result.setSuccess(true);
		}
		return result;
	}

     /**
      * 新增用户角色作用域
      * @param sysUserRoleScope
      * @return
      */
	@PostMapping(value = "/addUserRoleScope")
    public Result addUserRoleScope(@RequestBody SysUserRoleScope sysUserRoleScope){
        long start = System.currentTimeMillis();
        Result<String> result = new Result<>();
        try {
            this.sysUserRoleService.addUserRoleScope(sysUserRoleScope);
            log.info("======作用域授权成功=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
            return Result.ok("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("授权失败！");
        }
    }

     /**
      * 编辑用户角色作用域
      * @param sysUserRoleScope
      * @return
      */
	@PutMapping(value = "/editUserRoleScope")
    public Result editUserRoleScope(@RequestBody SysUserRoleScope sysUserRoleScope){
        long start = System.currentTimeMillis();
        Result<String> result = new Result<>();
        try {
            this.sysUserRoleService.editUserRoleScope(sysUserRoleScope);
            log.info("======作用域授权成功=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
            return Result.ok("编辑成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("系统繁忙,编辑失败！");
        }
    }





     /**
      * 用户角色授权功能，查询角色权限树
      * @param request
      * @return
      */
     @RequestMapping(value = "/queryRoleTreeList", method = RequestMethod.GET)
     public Result<Map<String,Object>> queryRoleTreeList(HttpServletRequest request) {
         Result<Map<String,Object>> result = new Result<>();
         //全部权限ids
         List<String> ids = new LinkedList<>();
         try {
             LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<SysRole>();
             query.eq(SysRole::getDelFlag, CommonConstant.DEL_FLAG_0);
             query.orderByAsc(SysRole::getRoleType);
             List<SysRole> list = sysRoleService.list(query);
             for(SysRole sysPer : list) {
                 ids.add(sysPer.getId());
             }
             List<TreeModel> treeList = new LinkedList<>();
             //选中的用户已拥有的角色
             List<SysUserRole> existRoleList = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, request.getParameter("userId")));
             Map<String,String> existRoleMap = new HashMap<>();
             for (SysUserRole sysUserRole:existRoleList){
                 existRoleMap.put(sysUserRole.getRoleId(),"-");
             }
             getRoleTreeModelList(treeList, list, existRoleMap,null);
             Map<String,Object> resMap = new HashMap<String,Object>();
             resMap.put("treeList", treeList); //全部树节点数据
             resMap.put("ids", ids);//全部树ids
             result.setResult(resMap);
             result.setSuccess(true);
         } catch (Exception e) {
             log.error(e.getMessage(), e);
         }
         return result;
     }


     /**
      * 用户角色授权功能，查询作用域权限树
      * @param request
      * @return
      */
     @RequestMapping(value = "/queryScopeTreeList", method = RequestMethod.GET)
     public Result<Map<String,Object>> queryScopeTreeList(HttpServletRequest request) {
         Result<Map<String,Object>> result = new Result<>();
         //全部权限ids
         List<String> ids = new LinkedList<>();
         try {
             LambdaQueryWrapper<SysScope> query = new LambdaQueryWrapper<SysScope>();
             query.eq(SysScope::getDelFlag, CommonConstant.DEL_FLAG_0);
             query.orderByAsc(SysScope::getScopeType);
             query.orderByDesc(SysScope::getCreateTime);
             List<SysScope> list = sysScopeService.list(query);
             for(SysScope sysPer : list) {
                 ids.add(sysPer.getId());
             }
             List<TreeModel> treeList = new LinkedList<>();
             getScopeTreeModelList(treeList, list, null);
             Map<String,Object> resMap = new HashMap<String,Object>();
             resMap.put("treeList", treeList); //全部树节点数据
             resMap.put("ids", ids);//全部树ids
             result.setResult(resMap);
             result.setSuccess(true);
         } catch (Exception e) {
             log.error(e.getMessage(), e);
         }
         return result;
     }

     /**
      * 查询用户已有的角色和作用域权限
      *
      * @return
      */
     @RequestMapping(value = "/queryUserRoleScope", method = RequestMethod.GET)
     public Result<Map<String,List<String>>> queryUserRoleScope(
             @RequestParam(name = "userId", required = true) String userId,
             @RequestParam(name = "roleId",required = false) String roleId) {
         try {
             List<SysUserRole> list = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userId));
             Map<String,List<String>> resMap = new HashMap<>();
             List<String> roleList = new ArrayList<>();
             List<String> scopeList = new ArrayList<>();
             List<String> existRoleList = new ArrayList<>();
             for (SysUserRole sysUserRole:list){
                 existRoleList.add(sysUserRole.getRoleId());
                 if (StringUtils.isNotBlank(roleId) && roleId.equals(sysUserRole.getRoleId())){
                     scopeList.add(sysUserRole.getScopeId());
                 }
             }
             roleList.add(roleId);
             resMap.put("roleList",roleList);
             resMap.put("scopeList",scopeList);
             resMap.put("existRoleList",existRoleList);
             return Result.ok(resMap);
         } catch (Exception e) {
             log.error(e.getMessage(), e);
             return Result.error("系统繁忙,请稍后再试");
         }
     }

     private void getRoleTreeModelList(List<TreeModel> treeList,List<SysRole> metaList,Map<String,String> existRoleMap,TreeModel temp) {
         for (SysRole permission : metaList) {
             String tempPid = permission.getParentId();
             if (DataScopeEnum.DATA_SCOPE_TENANT_ADMIN.getCode() == permission.getRoleType()){
                    permission.setRoleName(permission.getRoleName() +"[系统管理员]") ;
             }
             if (existRoleMap.containsKey(permission.getId())){
                 permission.setRoleName(permission.getRoleName() + "(已拥有)");
             }
             TreeModel tree = new TreeModel(permission.getId(), tempPid, permission.getRoleName(),0, true);
             if(temp==null && oConvertUtils.isEmpty(tempPid)) {
                 treeList.add(tree);
                 if(!tree.isLeaf()) {
                     getRoleTreeModelList(treeList, metaList,existRoleMap, tree);
                 }
             }else if(temp!=null && tempPid!=null && tempPid.equals(temp.getKey())){
                 temp.getChildren().add(tree);
                 if(!tree.isLeaf()) {
                     getRoleTreeModelList(treeList, metaList,existRoleMap, tree);
                 }
             }
         }
     }
     private void getScopeTreeModelList(List<TreeModel> treeList,List<SysScope> metaList,TreeModel temp) {
         for (SysScope permission : metaList) {
             String tempPid = permission.getParentId();
             TreeModel tree = new TreeModel(permission.getId(), tempPid, permission.getScopeName(),0, true);
             if(temp==null && oConvertUtils.isEmpty(tempPid)) {
                 treeList.add(tree);
                 if(!tree.isLeaf()) {
                     getScopeTreeModelList(treeList, metaList, tree);
                 }
             }else if(temp!=null && tempPid!=null && tempPid.equals(temp.getKey())){
                 temp.getChildren().add(tree);
                 if(!tree.isLeaf()) {
                     getScopeTreeModelList(treeList, metaList, tree);
                 }
             }
         }
     }

	//===========================以下是子表信息操作相关API====================================
	
	/**
	  * 通过主表id查询用户岗位表
	 * @param mainId
	 * @return
	 */
	@GetMapping(value = "/listSysUserPositionByMainId")
	public Result<List<SysUserPosition>> listSysUserPositionByMainId(@RequestParam(name="mainId",required=false) String mainId,
                                                                          @RequestParam(value = "menuPath",required = true) String menuPath) {
		Result<List<SysUserPosition>> result = new Result<List<SysUserPosition>>();
		List<SysUserPosition> sysUserPositionList = null;
		if (mainId != null) {
            String sqlMap = sysUserRoleService.dataScopeDepartOnlyFilter(SsoUtil.getLoginUser(),"d",menuPath,"a",null);
			sysUserPositionList = sysUserPositionService.selectByMainId(mainId,sqlMap);
            for (SysUserPosition sup:sysUserPositionList) {
                if (StringUtils.isNotBlank(sup.getParentIds())){
                    String[] parentIdArr =  sup.getParentIds().split(",");
                    for (int i=parentIdArr.length -1; i>=0;i--){
                        SysDepart parentDepart = sysDepartService.getById(parentIdArr[i]);
                        if (parentDepart == null) continue;
                        if (CommonConstant.DEPART_PROPERTY_OFFICE.equals(parentDepart.getDepartProperty())){
                            sup.setOfficeName(parentDepart.getDepartName());
                        } else if (CommonConstant.DEPART_PROPERTY_COMPANY.equals(parentDepart.getDepartProperty())){
                            if (StringUtils.isBlank(sup.getOfficeName())){
                                sup.setOfficeName("-");
                            }
                            sup.setCompanyName(parentDepart.getDepartName());
                            break;
                        }
                    }
                } else {
                    sup.setOfficeName("-");
                }
                String departPositionId = sup.getDepartPositionId();
                if (StringUtils.isNotEmpty(departPositionId)){
                    ArrayList<String> objects = new ArrayList<>();
                    objects.add(departPositionId);
                    sup.setReceiveAttr(objects);
                }
            }
            result.setResult(sysUserPositionList);
            result.setSuccess(true);
            return result;
		}else return null;	
	}

    
    /**
     * 编辑用户岗位表
     *
     * @return
     */
    @PutMapping("/editSysUserPosition")
    public Result<SysUserPosition> editSysUserPosition(@RequestBody Map<String,Object> map) {
        System.out.println(map);
        Result<SysUserPosition> result = new Result<>();
        String receiveAttr = (String) map.get("receiveAttr");
        SysDepartPosition sysDepartPosition = sysDepartPositionService.selectById(receiveAttr);
        SysUserPosition sysUserPosition = new SysUserPosition();
        sysUserPosition.setPositionId(sysDepartPosition.getPositionId());
        sysUserPosition.setDepartPositionId(receiveAttr);
        sysUserPosition.setDepartId((String) map.get("departId"));
        sysUserPosition.setId((String) map.get("id"));
        try {
        Integer count = sysUserPositionService.selectByDepartPositionId(receiveAttr, (String) map.get("userId"));
        if (count > 0){
            result.setMessage("该用户在所选部门已有该职位");
            return  result;
        }
        sysUserPositionService.updateById(sysUserPosition);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("更新数据过程中出现异常啦: " + e.getMessage());
            return result;
        }
        return result;
    }
    
    /**
     * 通过id删除用户岗位表
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/deleteSysUserPosition")
    public Result<SysUserPosition> deleteSysUserPosition(@RequestParam(name = "id", required = true) String id) {
        Result<SysUserPosition> result = new Result<>();
        try {
            boolean ok = sysUserPositionService.removeById(id);
            if (ok) {
                result.setSuccess(true);
                result.setMessage("删除用户岗位表成功.");
            } else {
                result.setSuccess(false);
                result.setMessage("删除用户岗位表失败!");
            }
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("删除用户岗位表过程中出现异常啦: " + e.getMessage());
            return result;
        }
    }
	
	/**
     * 批量删除用户岗位表
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatchSysUserPosition")
    public Result<SysUserPosition> deleteBatchSysUserPosition(@RequestParam(name = "ids", required = true) String ids) {
        Result<SysUserPosition> result = new Result<SysUserPosition>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.sysUserPositionService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }
    
	/**
	  * 通过主表id查询用户角色表
	 * @param mainId
	 * @return
	 */
	@GetMapping(value = "/listSysUserRoleByMainId")
	public Result<List<SysUserRoleScopeResponse>> listSysUserRoleByMainId(@RequestParam(name="mainId",required=false) String mainId) {
		Result<List<SysUserRoleScopeResponse>> result = new Result<List<SysUserRoleScopeResponse>>();
		if (mainId != null) {
            List<SysUserRole> list = sysUserRoleService.selectByMainId(mainId);
            Map<String,SysUserRoleScopeResponse> map = new HashMap<>();
            for (SysUserRole sysUserRole: list){
                SysUserRoleScopeResponse response = map.get(sysUserRole.getRoleId());
                if (response != null){
                    response.setScopeNames(response.getScopeNames() + "</br>" + sysUserRole.getScopeName());
                    response.setIds(response.getIds() + "," + sysUserRole.getId());
                } else {
                    map.put(sysUserRole.getRoleId(),new SysUserRoleScopeResponse(sysUserRole));
                }
            }
            List<SysUserRoleScopeResponse> responseList =  new ArrayList<>(map.values());
            result.setResult(responseList);
            result.setSuccess(true);
            return result;
		}else return null;	
	}
	
	/**
     * 添加用户角色表
     *
     * @param sysUserRole
     * @return
     */
    @PostMapping(value = "/addSysUserRole")
    public Result<SysUserRole> addSysUserRole(@RequestBody SysUserRole sysUserRole) {
        Result<SysUserRole> result = new Result<>();
        try {
            boolean ok = sysUserRoleService.save(sysUserRole);
            if (ok) {
                result.setSuccess(true);
                result.setMessage("添加用户角色表成功.");
            } else {
                result.setSuccess(false);
                result.setMessage("添加用户角色表失败!");
            }
            return result;
        } catch (Exception e) {
            e.fillInStackTrace();
            result.setSuccess(false);
            result.setMessage("添加用户角色表过程中出现了异常: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 编辑用户角色表
     *
     * @param sysUserRole
     * @return
     */
    @PutMapping("/editSysUserRole")
    public Result<SysUserRole> editSysUserRole(@RequestBody SysUserRole sysUserRole) {
        Result<SysUserRole> result = new Result<>();
        try {
            boolean ok = sysUserRoleService.updateById(sysUserRole);
            if (ok) {
                result.setSuccess(true);
                result.setMessage("更新用户角色表成功.");
            } else {
                result.setSuccess(false);
                result.setMessage("更新用户角色表失败!");
            }
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("更新数据过程中出现异常啦: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 通过id删除用户角色表
     *
     * @param ids (角色做了合并展示 ids)
     * @return
     */
    @DeleteMapping(value = "/deleteSysUserRole")
    public Result<SysUserRole> deleteSysUserRole(@RequestParam(name = "id", required = true) String ids) {
        Result<SysUserRole> result = new Result<>();
        try {
            List<String> idList = Arrays.asList(ids.split(","));
            LambdaQueryWrapper<SysUserRole> query = new LambdaQueryWrapper<SysUserRole>();
            query.in(SysUserRole::getId,idList);
            List<SysUserRole>  delList = sysUserRoleService.list(query);
            boolean ok =  sysUserRoleService.remove(query);
            //将删除记录保持到历史表中
            for (SysUserRole userRole:delList){
                userRole.setUpdateBy(SsoUtil.getLoginUser().getId());
                userRole.setUpdateTime(new Date());
            }
            if (delList.size() > 0){
                sysUserRoleService.insertBatchHis(delList);
            }
            if (ok) {
                result.setSuccess(true);
                result.setMessage("删除用户角色表成功.");
            } else {
                result.setSuccess(false);
                result.setMessage("删除用户角色表失败!");
            }
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("删除用户角色表过程中出现异常啦: " + e.getMessage());
            return result;
        }
    }


	/**
     * 批量删除用户角色表
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatchSysUserRole")
    public Result<SysUserRole> deleteBatchSysUserRole(@RequestParam(name = "ids", required = true) String ids) {
        Result<SysUserRole> result = new Result<SysUserRole>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.sysUserRoleService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }
    

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response,SysUser sysUser) {
        // Step.1 组装查询条件
        QueryWrapper<SysUser> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                SysUser sysUserTemp = JSON.parseObject(deString, SysUser.class);
                queryWrapper = QueryGenerator.initQueryWrapper(sysUserTemp, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysUserPage> pageList = new ArrayList<SysUserPage>();
        List<SysUser> sysUserList = sysUserService.list(queryWrapper);
        for (SysUser sysUserTemp : sysUserList) {
            SysUserPage vo = new SysUserPage();
            BeanUtils.copyProperties(sysUserTemp, vo);
            List<SysUserPosition> sysUserPositionList = sysUserPositionService.selectByMainId(sysUserTemp.getId(),sysUser.getSqlMap());
            vo.setSysUserPositionList(sysUserPositionList);
            List<SysUserRole> sysUserRoleList = sysUserRoleService.selectByMainId(sysUserTemp.getId());
            vo.setSysUserRoleList(sysUserRoleList);
            pageList.add(vo);
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户管理列表");
        mv.addObject(NormalExcelConstants.CLASS, SysUserPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户管理列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SysUserPage> list = ExcelImportUtil.importExcel(file.getInputStream(), SysUserPage.class, params);
                for (SysUserPage page : list) {
                    SysUser po = new SysUser();
                    BeanUtils.copyProperties(page, po);
                    sysUserService.saveMain(po, page.getSysUserPositionList(),page.getSysUserRoleList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                return Result.error("文件导入失败:"+e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }
     /**
      * 添加用户岗位
      *
      */
     @RequestMapping("addUserPosition")
     public Result<?> addUserPosition(@RequestBody Map<String,Object> map){
         Result<Object> result = new Result<>();
         String userId = (String) map.get("mainId");
         List<String> departPositionList = ( List<String>)map.get("receiveAttr");
         String departId = (String)map.get("departId");
          try {
              List<SysDepartPosition> sdp = new ArrayList<>();
              List<SysDepartPosition> sysDepartPositions = sysDepartPositionService.selectPositionList(departPositionList);
              //获取人员所入部门岗位
              List<SysUserPosition> sysUserPositionList = sysUserPositionService.selectDepartPosition(userId);
              for (SysDepartPosition sp:sysDepartPositions) {
                  for (SysUserPosition sup:sysUserPositionList) {
                      if (sp.getId().equals(sup.getDepartPositionId()) && sp.getDepartId().equals(sup.getDepartId())){
                           sdp.add(sp);
                      }
                  }
              }
              sysDepartPositions.removeAll(sdp);
              sysUserPositionService.addBatch(userId,departId,sysDepartPositions);
              result.setMessage("入岗成功");
          }catch (Exception e){
              e.printStackTrace();

          }
          return result;
          /*String userPositions = sysUserPositionService.selectPositionId(userId);
         if (StringUtils.isNotEmpty(userPositions)){
             List<String> userPositionsList = Arrays.asList(userPositions.split(","));
             List<String> s1=new ArrayList(userPositionsList);
             if (userPositionsList.size()>0){
                 List<String> newPositionIds = Arrays.asList(positionIds.split(","));
                 List<String> s2=new ArrayList(newPositionIds);
                 s2.removeAll(s1);
                 if (s2.size()>0){
                      positionIds = StringUtils.join(s2.toArray(), ",");
                 }else {
                      positionIds ="";
                 }
             }
         }

         SysUserPosition sysUserPosition = new SysUserPosition();
         sysUserPosition.setUserId(userId);
         sysUserPosition.setDepartId(departId);
         sysUserPosition.setPositionId(positionIds);
         SysUserPosition sysUserPosition1 = sysUserPositionService.existPosition(userId);
         String str = "";
         boolean flag = false;
         if (null != sysUserPosition1){
             if (StringUtils.isNotEmpty(positionIds)){
                 str =sysUserPosition1.getPositionId()+","+positionIds;
                 flag = sysUserPositionService.updatePosition(str, userId)>0;
             } else {
                 return Result.error("你所选的岗位已经配置");
             }
           }else{
          flag = sysUserPositionService.save(sysUserPosition);
          }
          result.setMessage("添加成功");
          result.setSuccess(flag);
          return result;*/
     }
     /**
      * 查找职位信息表所有的岗位
      */
     @RequestMapping("findAllPosition")
     public Result<List<SysPosition>> findAllPosition(){
         Result<List<SysPosition>> result = new Result<>();
         List<SysPosition> list = sysPositionService.list();
         result.setResult(list);
         return result;
     }
     /**
      * 用户角色添加
      */
     @RequestMapping("addUserRole")
     public  Result<?> addUserRole(@RequestBody Map<String,Object> map){
         Result<Object> result = new Result<>();
         String mainId = (String) map.get("mainId");
         String roleId =   map.get("roleId").toString().replace("[","").replace("]","");
         if (StringUtils.isEmpty(mainId)){
             return  Result.error("请选择需要添加的角色的用户");
         }
         if (StringUtils.isEmpty(roleId)){
             return Result.error("请选择需要添加的角色");
         }
         SysUserRole sysUserRole = new SysUserRole();
         sysUserRole.setUserId(mainId);
         sysUserRole.setRoleId(roleId);
         boolean save = sysUserRoleService.save(sysUserRole);
         result.setSuccess(save);
         return result;
     }
     /**
      * 所有角色列表信息
      */
     @RequestMapping("getAllRoleList")
     public Result<List<SysRole>> getAllRoleList(){
         Result<List<SysRole>> listResult = new Result<>();
         List<SysRole> list = sysRoleService.list();
         listResult.setResult(list);
         return listResult;
     }
}
